<template>
  <div class="contract-detail">
    <van-skeleton title :row="5" :loading="loading">
      <van-form ref="form" @submit="formSubmited">
        <!-- <van-field
        v-model="form.serialNum"
        name="serialNum"
        label="编号"
        placeholder="保存后自动生成编号"
        disabled
        v-show="pageType == 1"
        />-->

        <van-field
          v-model="form.contractNum"
          name="contractNum"
          label="合同号"
          placeholder="请输入合同号"
          :rules="[
            {
              validator: contractNumVali,
              message: '合同号只能由数字和字母组成',
            },
          ]"
          :disabled="!canEdit"
        />

        <van-field
          v-model="showForm.cusAddDocumentId_show"
          name="cusAddDocumentId"
          label="客户名称"
          placeholder="请选择客户名称"
          required
          readonly
          clickable
          :rules="[
            { validator: cusAddDocsValidate, message: '请输入正确内容' },
          ]"
          :disabled="!canEdit"
          @click="openFuzzyPopup('cusAddDocumentId', 'cusFullName', false)"
        />
        <van-popup
          v-model="popupVisible"
          position="top"
          @opened="fuzzyPopupOpened"
        >
          <div class="salesmanPopupContainer">
            <van-search
              ref="popupDom"
              v-model="searchValue"
              placeholder="请输入搜索关键词"
              :show-action="showSearchAdd"
              @input="fuzzyInput"
              @clear="fuzzyClear"
            >
              <template #action>
                <div @click="fuzzyAdd" style="color: #1989fa">添加/修改</div>
              </template>
            </van-search>
            <div class="salesmanItemContainer">
              <div
                v-for="item in searchArray"
                :key="'' + item.id + Math.random()"
                @click="fuzzyItemClick(item)"
                class="salesmanItem van-hairline--bottom"
              >
                {{ item[popupCtr.showKey] }}
              </div>
            </div>
          </div>
        </van-popup>

        <van-field
          v-model="showForm.projectReportId_show"
          name="projectReportId"
          placeholder="请选择项目名称"
          required
          readonly
          clickable
          :rules="[
            { validator: projectReportIdVali, message: '请输入正确内容' },
          ]"
          :disabled="!canEdit"
          @click="openFuzzyPopup('projectReportId', 'projectName', true)"
        >
          <template #label>
            <div>
              项目名称
              <span style="color: red">(需与T100保持一致)</span>
            </div>
          </template>
        </van-field>

        <van-field
          v-model="showForm.salesmanId_show"
          name="salesmanId"
          label="跟进业务员"
          placeholder="请选择跟进业务员"
          required
          readonly
          clickable
          :rules="[{ validator: salesmanValidate, message: '请输入正确内容' }]"
          :disabled="!canEdit"
          @click="openFuzzyPopup('salesmanId', 'nickName')"
        />

        <van-tabs :border="false">
          <van-tab title="节点 1">
            <van-field
              readonly
              clickable
              name="projectNode1Status"
              :value="showForm.projectNode1Status_show"
              label="项目节点1"
              placeholder="点击选择项目节点1"
              :rules="[
                {
                  required: true,
                  message: '请选择项目节点1',
                  trigger: 'onChange',
                },
              ]"
              required
              :disabled="!canEdit"
              @click="openNodePicker('projectNode1Status')"
            />
            <van-field
              v-model="form.projectNode1CollectRatio"
              name="projectNode1CollectRatio"
              label="项目节点1进度收款比例(%)"
              placeholder="请输入"
              required
              type="number"
              :disabled="!canEdit"
            />

            <van-field
              v-model="form.projectNode1LatestMonth"
              name="projectNode1LatestMonth"
              label="项目节点1最迟收款基准月数"
              placeholder="请输入"
              required
              type="number"
              :disabled="!canEdit"
            />
          </van-tab>
          <van-tab title="节点 2">
            <van-field
              readonly
              clickable
              name="projectNode2Status"
              :value="showForm.projectNode2Status_show"
              label="项目节点2"
              placeholder="点击选择项目节点2"
              :rules="[
                {
                  required: true,
                  message: '请选择项目节点1',
                  trigger: 'onChange',
                },
              ]"
              :disabled="!canEdit"
              @click="openNodePicker('projectNode2Status')"
            />

            <van-field
              v-model="form.projectNode2CollectRatio"
              name="projectNode2CollectRatio"
              label="项目节点2进度收款比例(%)"
              placeholder="请输入"
              type="number"
              :disabled="!canEdit"
            />

            <van-field
              v-model="form.projectNode2LatestMonth"
              name="projectNode2LatestMonth"
              label="项目节点2最迟收款基准月数"
              placeholder="请输入"
              type="number"
              :disabled="!canEdit"
            />
          </van-tab>
          <van-tab title="节点 3">
            <van-field
              readonly
              clickable
              name="projectNode3Status"
              :value="showForm.projectNode3Status_show"
              label="项目节点3"
              placeholder="点击选择项目节点3"
              :rules="[
                {
                  required: true,
                  message: '请选择项目节点3',
                  trigger: 'onChange',
                },
              ]"
              :disabled="!canEdit"
              @click="openNodePicker('projectNode3Status')"
            />

            <van-field
              v-model="form.projectNode3CollectRatio"
              name="projectNode3CollectRatio"
              label="项目节点3进度收款比例(%)"
              placeholder="请输入"
              type="number"
              :disabled="!canEdit"
            />

            <van-field
              v-model="form.projectNode3LatestMonth"
              name="projectNode3LatestMonth"
              label="项目节点3最迟收款基准月数"
              placeholder="请输入"
              type="number"
              :disabled="!canEdit"
            />
          </van-tab>
          <van-tab title="节点 4">
            <van-field
              readonly
              clickable
              name="projectNode4Status"
              :value="showForm.projectNode4Status_show"
              label="项目节点4"
              placeholder="点击选择项目节点4"
              :rules="[
                {
                  required: true,
                  message: '请选择项目节点4',
                  trigger: 'onChange',
                },
              ]"
              :disabled="!canEdit"
              @click="openNodePicker('projectNode4Status')"
            />

            <van-field
              v-model="form.projectNode4CollectRatio"
              name="projectNode4CollectRatio"
              label="项目节点4进度收款比例(%)"
              placeholder="请输入"
              type="number"
              :disabled="!canEdit"
            />

            <van-field
              v-model="form.projectNode4LatestMonth"
              name="projectNode4LatestMonth"
              label="项目节点4最迟收款基准月数"
              placeholder="请输入"
              type="number"
              :disabled="!canEdit"
            />
          </van-tab>
          <van-tab title="节点 5">
            <van-field
              readonly
              clickable
              name="projectNode5Status"
              :value="showForm.projectNode5Status_show"
              label="项目节点5"
              placeholder="点击选择项目节点5"
              :rules="[
                {
                  required: true,
                  message: '请选择项目节点5',
                  trigger: 'onChange',
                },
              ]"
              :disabled="!canEdit"
              @click="openNodePicker('projectNode5Status')"
            />

            <van-field
              v-model="form.projectNode5CollectRatio"
              name="projectNode5CollectRatio"
              label="项目节点5进度收款比例(%)"
              placeholder="请输入"
              type="number"
              :disabled="!canEdit"
            />

            <van-field
              v-model="form.projectNode5LatestMonth"
              name="projectNode5LatestMonth"
              label="项目节点5最迟收款基准月数"
              placeholder="请输入"
              type="number"
              :disabled="!canEdit"
            />
          </van-tab>
        </van-tabs>

        <van-popup v-model="projectNodePickerVisible" position="bottom">
          <van-picker
            show-toolbar
            :columns="projectNodeStatusDict"
            @confirm="onSelectConfirm"
            @cancel="projectNodePickerVisible = false"
          />
        </van-popup>

        <van-field
          readonly
          clickable
          name="contractDate"
          :value="form.contractDate"
          label="合同日期"
          placeholder="点击选择日期"
          required
          :disabled="!canEdit"
          :rules="[
            { required: true, message: '请选择合同日期', trigger: 'onChange' },
          ]"
          @click="canEdit ? (contractDateShow = true) : false"
        />
        <van-calendar
          ref="calendar"
          v-model="contractDateShow"
          @confirm="contractDateConfirm"
          :default-date="contractDateDefaultDate"
        />

        <van-field
          v-model="form.agentDiscountRate"
          name="agentDiscountRate"
          label="代理商折扣比例(%)"
          placeholder="请输入"
          type="number"
          :rules="[
            {
              validator: agentDIscountRateVali,
              message: '代理商折扣比例需在0~100',
            },
          ]"
          :disabled="!canEdit"
        />

        <van-field
          v-model="form.firstAcceptanceLatestMonth"
          name="firstAcceptanceLatestMonth"
          label="首次出货验收最迟收款基准月数"
          placeholder="请输入"
          type="number"
          required
          :disabled="!canEdit"
        />

        <van-field
          v-model="form.contractAmount"
          name="contractAmount"
          label="合同金额"
          placeholder="请输入"
          type="number"
          required
          :rules="[
            { validator: contractAmountVali, message: '请输入合同金额' },
          ]"
          :disabled="!canEdit"
        />

        <van-field
          v-if="pageType == 1"
          v-model="form.margin"
          name="margin"
          label="保证金"
          placeholder="请输入"
          type="number"
          :disabled="!canEdit"
        />

        <van-field
          v-if="pageType == 1"
          v-model="form.totalReceivableAmount"
          name="totalReceivableAmount"
          label="总应收金额"
          placeholder="请输入"
          type="number"
          :disabled="!canEdit"
        />

        <van-field
          v-if="pageType == 1"
          v-model="form.receivedAmount"
          name="receivedAmount"
          label="已收金额"
          placeholder="请输入"
          type="number"
          :disabled="!canEdit"
        />

        <van-field
          v-if="pageType == 1"
          v-model="form.totalOverdueAmount"
          name="totalOverdueAmount"
          label="逾期总金额"
          placeholder="请输入"
          type="number"
          :disabled="!canEdit"
        />

        <van-field
          v-if="pageType == 1"
          v-model="form.adjustAmount"
          name="adjustAmount"
          label="调整金额"
          placeholder="请输入"
          type="number"
          :disabled="!canEdit"
        />

        <van-field
          v-if="pageType == 1"
          v-model="form.warrantyOverAmount"
          name="warrantyOverAmount"
          label="质保金逾期金额"
          placeholder="请输入"
          type="number"
          :disabled="!canEdit"
        />

        <van-field
          v-if="pageType == 1"
          v-model="form.modelRoomOverAmount"
          name="modelRoomOverAmount"
          label="样板房逾期金额"
          placeholder="请输入"
          type="number"
          :disabled="!canEdit"
        />

        <van-field readonly label="型号">
          <!-- <template #button>
            <van-button
              size="small"
              type="primary"
              native-type="button"
              :disabled="!canEdit"
              @click="openLockModal(undefined)"
              >添加型号</van-button
            >
          </template> -->
        </van-field>

        <v-table
          is-horizontal-resize
          style="width: 100%"
          :columns="lockModalCol"
          :table-data="lockModelArr"
          row-hover-color="#eee"
          row-click-color="#edf7ff"
          :row-click="lockItemClick"
        ></v-table>

        <van-field readonly label="出货信息"></van-field>

        <v-table
          is-horizontal-resize
          is-vertical-resize
          :min-height="200"
          style="width: 100%"
          :columns="shipmentCol"
          :table-data="shipmentData"
          row-hover-color="#eee"
          row-click-color="#edf7ff"
          :row-click="shipmentItemClick"
        ></v-table>
      </van-form>
    </van-skeleton>
    <div style="margin: 0.3rem" v-if="recordCanEdit">
      <van-row type="flex">
        <van-col class="bottomBtnCol" v-if="pageType == 1">
          <van-button
            round
            block
            type="default"
            native-type="button"
            @click="canEditBtnClick"
            >{{ canEdit ? "取消" : "编辑" }}</van-button
          >
        </van-col>
        <van-col class="bottomBtnCol">
          <van-button
            round
            block
            type="info"
            native-type="button"
            :disabled="!canEdit"
            @click="okBtnClick"
            >确定</van-button
          >
        </van-col>
      </van-row>
    </div>
    <van-popup v-model="lockModalVisible" :close-on-click-overlay="false">
      <div class="lockModalContainer">
        <div class="lockModalTitle">{{ lockModalTitle }}</div>
        <van-field
          v-model="lockPopop.model"
          readonly
          label="型号"
          placeholder="请输入型号"
        />
        <van-field
          v-model="lockPopop.color"
          readonly
          label="颜色"
          placeholder="请输入颜色"
        />
        <van-field
          v-model="lockPopop.quantity"
          readonly
          label="数量（套）"
          type="number"
          placeholder="请输入数量（套）"
        />
        <van-field
          v-model="lockPopop.price"
          readonly
          label="价格"
          type="number"
          placeholder="请输入价格"
        />
        <van-field
          readonly
          :value="lockPopop.estimateInstallYear"
          label="预计交楼年份"
          placeholder="点击选择预计交楼年份"
        />
        <van-field
          readonly
          name="estimateInstallYear"
          :value="lockPopop.estimateInstallMonth"
          label="预计交楼月份"
          placeholder="点击选择预计交楼月份"
        />
        <van-row type="flex" justify="end" class="lockModalBtnContainer">
          <van-button
            size="small"
            class="lockModalBtn"
            @click="lockModalVisible = false"
            >关闭</van-button
          >
          <!-- <van-button
            size="small"
            type="danger"
            class="lockModalBtn"
            :disabled="lockCurIndex == -1"
            @click="deleteLockItem"
            >删除</van-button
          >
          <van-button
            size="small"
            type="info"
            class="lockModalBtn"
            @click="saveLockModel"
            >保存</van-button
          > -->
        </van-row>
      </div>
    </van-popup>

    <van-popup v-model="shipmentModalVisible" :close-on-click-overlay="false">
      <div class="lockModalContainer shipmentModal">
        <div class="lockModalTitle van-hairline--bottom">出货信息</div>
        <div class="shipmentContent">
          <van-field
            v-model="shipmentPopup.deliveryOrderNo"
            label="出货单号"
            readonly
          />
          <van-field v-model="shipmentPopup.itemNum" label="顶次" readonly />
          <van-field
            v-model="shipmentPopup.materialNum"
            label="物料编号"
            readonly
          />
          <van-field
            v-model="shipmentPopup.specification"
            label="规格"
            type="textarea"
            readonly
          />
          <van-field
            v-model="shipmentPopup.quantity"
            label="出货数量"
            type="number"
            readonly
          />
          <van-field v-model="shipmentPopup.unitPrice" label="单价" type="number" readonly />
          <van-field
            v-model="shipmentPopup.shipmentAmount"
            label="出货金额"
            type="number"
            readonly
          />
          <van-field
            v-model="shipmentPopup.postingDate"
            label="过账日期"
            readonly
          />
          <van-field
            v-model="shipmentPopup.nodeBelong"
            label="节点归属"
            readonly
          />
          <van-field
            v-model="shipmentPopup.receivableAmount"
            label="节点应收金额"
            type="number"
            readonly
          />
          <van-field
            v-model="shipmentPopup.expectCollectDate"
            label="预计最后收款日期"
            readonly
          />
          <van-field
            v-model="shipmentPopup.isModelRoom"
            label="是否样板房"
            readonly
          />
          <van-field
            v-model="shipmentPopup.unAcceptanceNum"
            label="未验收数量"
            type="number"
            readonly
          />
        </div>
        <van-row type="flex" justify="end" class="lockModalBtnContainer">
          <van-button
            size="small"
            class="lockModalBtn"
            @click="shipmentModalVisible = false"
            >关闭</van-button
          >
        </van-row>
      </div>
    </van-popup>
  </div>
</template>

<script>
import Card from "@/components/Card";
import { _projectNodeStatusDict } from "@/utils/dict";
import { mapActions, mapMutations } from "vuex";
import {
  Skeleton,
  Form,
  Field,
  Picker,
  Calendar,
  RadioGroup,
  Radio,
  Popup,
  Button,
  Search,
  NumberKeyboard,
  Toast,
  Row,
  Col,
  Tab,
  Tabs,
} from "vant";
import Fuse from "fuse.js";
import { formatDate, accAdd, accAddCurring } from "@/utils";
import Vue from "vue";
export default {
  components: {
    Card,
    [Skeleton.name]: Skeleton,
    [Form.name]: Form,
    [Field.name]: Field,
    [Picker.name]: Picker,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    [Button.name]: Button,
    [Search.name]: Search,
    [NumberKeyboard.name]: NumberKeyboard,
    [Row.name]: Row,
    [Col.name]: Col,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
  },
  data() {
    return {
      title: "",
      pageType: 0,
      loading: true,
      form: {
        contractNum: "",
        cusAddDocumentId: "",
        projectReportId: "",
        projectName: "",
        projectNode1Status: 0,
        projectNode1CollectRatio: "",
        projectNode1LatestMonth: "",
        projectNode2Status: 0,
        projectNode2CollectRatio: "",
        projectNode2LatestMonth: "",
        projectNode3Status: 0,
        projectNode3CollectRatio: "",
        projectNode3LatestMonth: "",
        projectNode4Status: 0,
        projectNode4CollectRatio: "",
        projectNode4LatestMonth: "",
        projectNode5Status: 0,
        projectNode5CollectRatio: "",
        projectNode5LatestMonth: "",
        contractDate: "",
        agentDiscountRate: 100,
        firstAcceptanceLatestMonth: "",
        contractAmount: "",
        lockModel: "",
        salesmanId: "",
      },

      tenderDateShow: false,
      brandQuantityShow: false,

      contractDateShow: false,

      // 表单项展示用数据
      showForm: {
        cusAddDocumentId_show: "",
        salesmanId_show: "",
        projectReportId_show: "",
        projectNode1Status_show: "",
        projectNode2Status_show: "",
        projectNode3Status_show: "",
        projectNode4Status_show: "",
        projectNode5Status_show: "",
      },
      // 模糊搜索用弹窗控制
      popupCtr: {
        formName: "",
        showKey: "",
      },
      searchValue: "",
      popupVisible: false,
      searchArray: [],
      showSearchAdd: false,

      projectNodeStatusDict: _projectNodeStatusDict,

      projectNodePickerVisible: false,
      nodePickerCache: {
        formName: "",
      },

      salesmanIdArrOrigin: [],
      cusAddDocumentIdArrOrigin: [],
      projectReportIdArrOrigin: [],

      tenderDateDefaultDate: new Date(),
      contractDateDefaultDate: new Date(),

      lockModelArr: [],
      lockModalCol: [
        {
          field: "model",
          title: "型号",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "color",
          title: "颜色",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
        {
          field: "quantity",
          title: "数量（套）",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 30,
        },
      ],
      lockPopop: {
        color: "",
        model: "",
        quantity: "",
      },
      lockModalVisible: false,
      lockModalTitle: "",
      lockCurIndex: -1,
      lockModelArrOrigin: [],

      shipmentCol: [
        {
          field: "deliveryOrderNo",
          title: "出货单号",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 70,
        },
        {
          field: "specification",
          title: "规格",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 70,
        },
        {
          field: "quantity",
          title: "出货数量",
          titleAlign: "center",
          columnAlign: "center",
          isResize: true,
          width: 10,
        },
      ],
      shipmentData: [],
      shipmentPopup: {},
      shipmentModalVisible: false,

      canEdit: false,
      recordCanEdit: true, // 作废或者审批拒绝则不能编辑
    };
  },
  created() {
    if (this.$route.query.type == "add") {
      this.pageType = 0;
      this.canEdit = true;
    } else {
      this.pageType = 1;
    }
  },
  mounted() {
    this.loading = true;
    this.initData();
  },
  beforeDestroy() {
    this.resetDocsDetail();
  },
  methods: {
    ...mapActions({
      getCusDocsList: "projectReport/getCusDocsList",
      querySalesman: "cusAddDocs/querySalesman",
      getProjectListByCusId: "bid/getProjectListByCusId",
      addContract: "contract/addContract",
      getLockModel: "contract/getLockModel",
      getManageMsg: "contract/getManageMsg",
      getShipmentData: "contract/getShipmentData",
      getLockModelListByProId: "contract/getLockModelListByProId",
    }),
    ...mapMutations({
      resetDocsDetail: "contract/resetDocsDetail",
      setDocsDetail: "contract/setDocsDetail",
    }),
    initData() {
      let detail = this.$store.state.contract.docsDetail;
      if (this.pageType == 1) {
        this.recordCanEdit = false;
        this.canEdit = false;
      }
      if (this.pageType == 1) {
        for (const key in detail) {
          if (detail.hasOwnProperty(key)) {
            const element = detail[key];
            this.form[key] = "" + element;
          }
        }
        let projectNodeStatusDict = Vue.filter("projectNodeStatusDict");
        this.showForm.projectNode1Status_show = projectNodeStatusDict(
          this.form.projectNode1Status
        );
        this.showForm.projectNode2Status_show = projectNodeStatusDict(
          this.form.projectNode2Status
        );
        this.showForm.projectNode3Status_show = projectNodeStatusDict(
          this.form.projectNode3Status
        );
        this.showForm.projectNode4Status_show = projectNodeStatusDict(
          this.form.projectNode4Status
        );
        this.showForm.projectNode5Status_show = projectNodeStatusDict(
          this.form.projectNode5Status
        );
        this.form.contractDate = formatDate(
          new Date(detail.contractDate),
          "yyyy-MM-dd"
        );
        this.showForm.projectReportId_show = this.form.projectName;
        // this.getLockModel({ id: this.form.id })
        //   .then((res) => {
        //     console.log(res);
        //     if (res && res.data) {
        //       this.lockModelArr = res.data;
        //       this.lockModelArrOrigin = JSON.parse(JSON.stringify(res.data));
        //     }
        //   })
        //   .catch((err) => {
        //     console.log(err);
        //   });
        this.getShipmentData({ projectReportId: this.form.projectReportId })
          .then((res) => {
            console.log(res);
            if (res && res.shipmentDetailList) {
              this.shipmentData = res.shipmentDetailList;
            }
          })
          .catch((err) => {
            console.log(err);
          });
        this.getLockList();
      }
      this.getCusDocsList()
        .then((res) => {
          let cusArr = res.data;
          if (cusArr.length) {
            this.cusAddDocumentIdArrOrigin = JSON.parse(JSON.stringify(cusArr));
            if (this.pageType == 1) {
              for (let i = 0, len = cusArr.length; i < len; i++) {
                if (cusArr[i].id == detail.cusAddDocumentId) {
                  this.showForm.cusAddDocumentId_show = cusArr[i].cusFullName;
                  break;
                }
              }
            }
          }

          this.$nextTick(() => {
            this.loading = false;
          });
        })
        .catch((err) => console.log(err));
      this.querySalesman()
        .then((res) => {
          let salesmanArr = res.data;
          if (salesmanArr.length) {
            this.salesmanIdArrOrigin = JSON.parse(JSON.stringify(salesmanArr));
            if (this.pageType == 1) {
              for (let i = 0, len = salesmanArr.length; i < len; i++) {
                if (salesmanArr[i].id == detail.salesmanId) {
                  this.showForm.salesmanId_show = salesmanArr[i].nickName;
                  break;
                }
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    refresh() {
      this.getManageMsg({
        id: this.$store.state.contract.docsDetail.id,
      })
        .then((res) => {
          console.log("refresh", res);
          this.form.agentDiscountRate = res.data.agentDiscountRate;
          this.setDocsDetail(res.data);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    salesmanValidate(val) {
      return this.form.salesmanId ? true : false;
    },
    cusAddDocsValidate(val) {
      return this.form.cusAddDocumentId ? true : false;
    },
    contractNumVali(val) {
      let reg = /^[0-9a-zA-Z]*$/g;
      return val ? (reg.test(val) ? true : false) : true;
    },
    contractAmountVali(val) {
      return val ? true : false;
    },
    projectReportIdVali() {
      return this.form.projectReportId ? true : false;
    },
    groupAreaVali(val) {
      return this.form.groupType == "1" ? (val ? true : false) : true;
    },
    agentDIscountRateVali(val) {
      return val >= 0 && val <= 100;
    },
    openNodePicker(nodeName) {
      if (this.canEdit) {
        this.nodePickerCache.formName = nodeName;
        this.projectNodePickerVisible = true;
      }
    },
    onSelectConfirm(value) {
      console.log(value);
      this.form[this.nodePickerCache.formName] = value.value;
      this.showForm[`${this.nodePickerCache.formName}_show`] = value.text;
      this.projectNodePickerVisible = false;
    },
    contractDateConfirm(date) {
      this.form.contractDate = formatDate(date, "yyyy-MM-dd");
      this.contractDateShow = false;
    },
    openFuzzyPopup(formName, showKey, showSearchAdd) {
      if (this.canEdit) {
        this.popupCtr.formName = formName;
        this.popupCtr.showKey = showKey;
        this.searchValue = "";
        this.searchArray = [];
        if (formName == "projectReportId") {
          this.searchValue = this.form.projectName;
        }
        this.showSearchAdd = showSearchAdd;
        this.popupVisible = true;
      }
    },
    fuzzyPopupOpened() {
      let child = this.$refs.popupDom.getElementsByTagName("input");
      child[0].focus();
    },
    fuzzyItemClick(item) {//模糊搜索选项点击
      console.log(item);
      this.form[this.popupCtr.formName] = item.id;
      this.showForm[`${this.popupCtr.formName}_show`] =
        item[this.popupCtr.showKey];
      if (this.popupCtr.formName == "cusAddDocumentId") {
        this.form.projectReportId = "";
        this.showForm.projectReportId_show = "";
        this.lockModelArr = [];
        this.form.projectName = "";
        this.getProjectListByCusId({ cusAddDocumentId: item.id })
          .then((res) => {
            if (res) {
              console.log(res);
              this.projectReportIdArrOrigin = res;
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
      if (this.popupCtr.formName == "projectReportId") {
        this.form.projectName = item[this.popupCtr.showKey];
        this.getLockList();
      }
      this.popupCtr.formName = "";
      this.popupCtr.showKey = "";
      this.searchValue = "";
      this.searchArray = [];
      this.popupVisible = false;
    },
    fuzzyInput(value) {//模糊搜索输入
      console.log("value", value);
      if (value == "") {
        this.searchArray = [];
      } else {
        const options = {
          includeScore: true,
          // Search in `author` and in `tags` array
          keys: [this.popupCtr.showKey],
        };
        const fuse = new Fuse(
          this[`${this.popupCtr.formName}ArrOrigin`],
          options
        );
        const result = fuse.search(value);
        this.searchArray = [];
        result.forEach((e) => {
          this.searchArray.push(e.item);
        });
      }
    },
    fuzzyClear() {
      console.log("clear");
      this.form[this.popupCtr.formName] = "";
      this.showForm[`${this.popupCtr.formName}_show`] = "";
      if (this.popupCtr.formName == "projectReportId") {
        this.form.projectName = "";
      }
    },
    fuzzyAdd() {//模糊搜索点添加
      if (this.searchValue) {
        // this.form[this.popupCtr.formName] = this.searchValue;
        if (this.popupCtr.formName == "projectReportId") {
          if (this.form.projectReportId == "") {
            return Toast("请先选择项目");
          }
          this.form.projectName = this.searchValue;
        }
        this.showForm[`${this.popupCtr.formName}_show`] = this.searchValue;
        this.popupVisible = false;
      }
    },
    getLockList() {
      this.lockModelArr = [];
      this.getLockModelListByProId({
        projectReportId: this.form.projectReportId,
      })
        .then((res) => {
          console.log(res);
          if (res && Array.isArray(res)) {
            this.lockModelArr = res;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    saveLockModel() {
      // 送样型号保存点击
      let obj = JSON.parse(JSON.stringify(this.lockPopop));
      if (this.lockCurIndex == -1) {
        this.lockModelArr.push(obj);
      } else {
        this.$set(this.lockModelArr, this.lockCurIndex, obj);
      }

      this.lockModalVisible = false;
    },
    resetLockPopop() {
      // 重置送样型号相关信息
      this.lockPopop = {
        model: "",
        quantity: "",
        color: "",
      };
      this.lockCurIndex = -1;
    },
    deleteLockItem() {
      //删除送样型号
      if (this.lockCurIndex > -1) {
        this.$delete(this.lockModelArr, this.lockCurIndex);
        this.lockModalVisible = false;
      }
    },
    lockItemClick(rowIndex, rowData, column) {
      // 送样型号表格项点击
      console.log(rowIndex, rowData, column);
      this.lockCurIndex = rowIndex;
      this.openLockModal(JSON.parse(JSON.stringify(rowData)));
    },
    openLockModal(item) {
      // if (this.canEdit) {
      if (item) {
        this.lockPopop = item;
        this.lockModalTitle = "查看送样型号";
      } else {
        this.resetLockPopop();
        this.lockModalTitle = "添加送样型号";
      }
      this.lockModalVisible = true;
      // }
    },
    shipmentItemClick(rowIndex, rowData, column) {
      console.log(rowData);
      if (rowData) {
        rowData.isModelRoom =
          rowData.isModelRoom === 1
            ? "是"
            : rowData.isModelRoom === 0
            ? "否"
            : "";
        this.shipmentPopup = rowData;
      }
      this.shipmentModalVisible = true;
    },
    tenderDateConfirm(date) {
      console.log(date);
      this.form.tenderDate = formatDate(date, "yyyy-MM-dd");
      this.tenderDateShow = false;
    },
    canEditBtnClick() {
      if (this.canEdit) {
        // 取消 还原数据
        this.form = {
          contractNum: "",
          cusAddDocumentId: "",
          projectReportId: "",
          projectName: "",
          projectNode1Status: 0,
          projectNode1CollectRatio: "",
          projectNode1LatestMonth: "",
          projectNode2Status: 0,
          projectNode2CollectRatio: "",
          projectNode2LatestMonth: "",
          projectNode3Status: 0,
          projectNode3CollectRatio: "",
          projectNode3LatestMonth: "",
          projectNode4Status: 0,
          projectNode4CollectRatio: "",
          projectNode4LatestMonth: "",
          projectNode5Status: 0,
          projectNode5CollectRatio: "",
          projectNode5LatestMonth: "",
          contractDate: "",
          agentDiscountRate: 100,
          firstAcceptanceLatestMonth: "",
          contractAmount: "",
          lockModel: "",
        };
        let detail = this.$store.state.contract.docsDetail;
        if (this.pageType == 1) {
          for (const key in detail) {
            if (detail.hasOwnProperty(key)) {
              const element = detail[key];
              this.form[key] = "" + element;
            }
          }
        }

        let cusArr = this.cusAddDocumentIdArrOrigin;
        for (let i = 0, len = cusArr.length; i < len; i++) {
          if (cusArr[i].id == detail.cusAddDocumentId) {
            this.showForm.cusAddDocumentId_show = cusArr[i].cusFullName;
            break;
          }
        }

        this.$nextTick(() => {
          let date = new Date(detail.tenderDate);
          this.tenderDateDefaultDate = date;
          this.$refs.calendar.reset();

          this.form.tenderDate = formatDate(date, "yyyy-MM-dd");
        });
      }
      this.canEdit = !this.canEdit;
    },
    okBtnClick() {
      this.$refs.form.submit();
    },
    formSubmited() {
      let nodeRateSum = accAddCurring(this.form.projectNode1CollectRatio)(
        this.form.projectNode2CollectRatio
      )(this.form.projectNode3CollectRatio)(this.form.projectNode4CollectRatio)(
        this.form.projectNode5CollectRatio
      );
      console.log(nodeRateSum);
      if (nodeRateSum != 100) {
        return Toast("项目节点进度收款比例之和必须等于100%");
      }
      if (this.lockModelArr.length == 0) {
        return Toast("送样型号不能为空");
      }
      let lockModelStr = JSON.stringify(this.lockModelArr);
      this.form.lockModel = lockModelStr;
      if (this.pageType == 0) {
        this.addContract(this.form)
          .then((res) => {
            console.log(res);
            if (res.success) {
              Toast.success("新建成功");
              this.$router.go(-1);
            } else {
              Toast.fail(`新建失败：${res.message}`);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        // this.updateProjectPurchase(this.form)
        //   .then(res => {
        //     console.log(res);
        //     if (res.success) {
        //       Toast.success("更新成功");
        //       // this.$router.go(-1);
        //     } else {
        //       Toast.fail(`更新失败：${res.message}`);
        //     }
        //   })
        //   .catch(err => {
        //     console.log(err);
        //   });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.contract-detail {
  .van-radio {
    margin-bottom: 8px;
  }
  .salesmanPopupContainer {
    max-height: 100vh;
    overflow: hidden;
    .salesmanItemContainer {
      overflow: auto;
      position: relative;
      max-height: 600px;
      .salesmanItem {
        padding: 8px 12px;
      }
    }
  }
  .lockModalContainer {
    width: 320px;
    .lockModalTitle {
      padding: 8px 8px 8px 12px;
      font-size: 20px;
    }
    .lockModalBtnContainer {
      margin: 8px;
      .lockModalBtn {
        margin-left: 8px;
      }
    }
  }
  .shipmentModal {
    max-height: 450px;
    display: flex;
    flex-direction: column;
    .shipmentContent {
      flex: 1;
      overflow: auto;
    }
  }
  .bottomBtnCol {
    flex: 1;
    padding: 8px;
  }
}
</style>